<template>
  <view class="team-container">
    <view class="tabList">
      <view
        v-for="item in tabs"
        :key="item.id"
        :class="{ tab: true, check: item.isCheck }"
        @click="changeTabs(item)"
      >
        {{ item.name }}
      </view>
    </view>
    <!-- 明细 -->
     <view class="serchbox">
      <view class="serch_box">
      <view>
        <label for="">订单编号：</label>
      </view>
      <view class="box">
        <input
          v-model="o_uid"
          placeholder="请输入订单编号"
          type="text"
          style="flex: 1"
          placeholder-style="color: #A5ADBA;fonts-size: 14px;font-weight:bold;"
          class="text_inp"
        />
        <view class="submitBtn" @click="secrchOrder">搜 索</view>
      </view>
     </view>
     </view>
     
     <view class="splitLine"></view>
    <view v-if="orderList && orderList.length > 0" class="members-container">
      <view
        v-for="(item, index) in orderList"
        :key="index"
        class="earning-item"
      >
        <view class="item_s">标题：{{ item.title }}</view>
        <view class="item_s">订单编号：{{ item.order_uid }}</view>
        <view class="item_s">付款时间：{{ item.time }}</view>

        <view class="item_s" v-if="item.yeDiaoInfo"
          >定制内容：{{ item.yeDiaoInfos.remark }}</view
        >
        <view
          class="item_s"
          style="box-sizing: border-box;"
          v-if="item.yeDiaoInfo && item.yeDiaoInfos.file != ''"
          >定制模版：<image
            @click="previewImage(item, 1)"
            :src="item.yeDiaoInfos.file"
            style="width: 110px; height: 110px;margin:3px"
          ></image>
          <view
            style="
              margin-left: 5px;
              color: #66cc99;
              position: relative;
              top: 20px;
              font-size: 12px;
            "
            >长按保存图片</view
          >
        </view>

        <view class="item_s upload" v-if="item.title == '叶雕'"
          >制作图片：
          <view
            v-if="
              item.yeDiaoInfo &&
              item.yeDiaoInfos.makePic &&
              item.yeDiaoInfos.makePic != ''
            "
            style="width: 110px; height: 110px;margin:3px"
          >
            <image
              @click="previewImage(item, 2)"
              :src="item.yeDiaoInfos.makePic"
              style="width: 110px; height: 110px;margin:3px"
            />
          </view>
          <Upload
            ref="uUpload"
            :action="uploadParams.action"
            :header="{
              Authorization: 'Bearer ' + token, // token
            }"
            height="200"
            upload-text="选择"
            :form-data="uploadForm"
            :limitType="uploadParams.limitType"
            :source-type="['album']"
            :max-count="uploadParams.maxCount"
            :type="uploadParams.uploadType"
            :uploadText="uploadParams.uploadText"
            :artworksType="uploadForm.type"
            :cateId="uploadForm.cate_id"
            del-bg-color="#56d39d"
            :auto-upload="false"
            @on-uploaded="uploadSuccess"
            @on-choose-complete="chooseComplete"
          ></Upload>
        </view>
        <view class="item_s upload" v-if="item.title == '叶雕'"
          >制作视频：
          <view
            @click="playVideo(item)"
            v-if="
              item.yeDiaoInfo &&
              item.yeDiaoInfos.makeVideo &&
              item.yeDiaoInfos.makeVideo != ''
            "
            style="width: 110px; height: 110px;margin:3px"
          >
            <video
              :controls="false"
              :autoplay="false"
              :show-play-btn="false"
              :show-center-play-btn="false"
              :show-fullscreen-btn="false"
              :enable-progress-gesture="false"
              :src="item.yeDiaoInfos.makeVideo"
              style="width: 110px; height: 110px;margin:3px"
              id="myVideo"
            />
          </view>
          <Upload
            ref="uploadv"
            :action="uploadParamsv.action"
            :header="{
              Authorization: 'Bearer ' + token, // token
            }"
            height="200"
            upload-text="选择"
            :form-data="uploadForm"
            :limitType="uploadParamsv.limitType"
            :source-type="['album']"
            :max-count="uploadParamsv.maxCount"
            :type="uploadParamsv.uploadType"
            :uploadText="uploadParamsv.uploadText"
            :artworksType="uploadForm.type"
            :cateId="uploadForm.cate_id"
            del-bg-color="#56d39d"
            :auto-upload="false"
            @on-uploaded="uploadSuccessv"
            @on-choose-complete="chooseComplete"
          ></Upload>
        </view>
        <view
          v-if="item.title == '叶雕'"
          class="submitbtn"
          @click="submitWork(item, index)"
          >提 交</view
        >
        <view
          class="concatU"
          @click="openConcat(item)"
          v-if="item.title == '叶雕'"
          >联系用户</view
        >
      </view>
    </view>
    <view v-else class="empty">
      <image
        style="width: 350rpx; height: 350rpx"
        src="https://img.alicdn.com/imgextra/i1/1888948409/O1CN01CSQqUP2BzNNzcB96v_!!1888948409.png"
        mode="scaleToFill"
      />
      <view class="empty-tips">
        <text>暂无数据</text>
      </view>
    </view>
    <view class="popup" v-if="popShow">
      <view class="back">
        <view class="chart" id="box" ref="box">
          <view v-for="(item, i) in chatList" class="chatList" :key="i">
            <view v-if="userInfo.id == item.u_id" class="rightText">
              <view class="textBox">{{ item.text }}</view
              ><view class="u_name">{{ item.u_name }}</view>
            </view>
            <view v-else class="leftText">
              <view class="u_name">{{ item.u_name }}</view
              ><view class="textBox">{{ item.text }}</view>
            </view>
            <view style="clear: both"></view>
          </view>
        </view>
        <view class="submit">
          <input
            v-model="text"
            placeholder="请输入"
            type="text"
            style="flex: 1"
            placeholder-style="color: #A5ADBA;fonts-size: 14px;font-weight:bold;"
            class="text_inp"
            focus
          />
          <view class="submitBtn" @click="sendMsg">发送</view>
        </view>
      </view>
      <image class="closeIcon" :src="closeIcon" @click="closePop" />
    </view>
    <view
      class="mask"
      v-if="popShow"
      @touchmove.stop.prevent="moveHandle"
    ></view>
  </view>
</template>
  
  <script>
import { getOrderList, updataUserMemberOrder } from "@/api/artworks";
import { memberOrderList } from "@/api/applet";
import { parseTime } from "@/utils/parseTime";
import { mapGetters } from "vuex";
import Upload from "@/components/upload/upload";
import config from "@/utils/config";
export default {
  components: {
    Upload,
  },
  data() {
    return {
      tabs: [
        {
          name: "售后订单",
          id: 1,
          isCheck: true,
        },
        {
          name: "达人定制订单",
          id: 2,
          isCheck: false,
        },
      ],
      orderList: [],
      orderInfo: null,
      chatList: [],
      popShow: false,
      text: "",
      closeIcon: require("../../static/image/close-icon.png"),
      timer: null,
      uploadParams: {
        limitType: ["png", "PNG", "jpg", "JPG", "jpeg", "webp"],
        maxCount: 1,
        uploadType: "image",
        action: `${config.baseApi}/client/upload/uploadImg`,
        fileList: [],
        uploadText: "支持png/jpg",
        artwroksTitle: "上传作品",
      },
      uploadParamsv: {
        maxCount: 1,
        uploadType: "video",
        action: `${config.baseApi}/client/upload/uploadImg`,
        fileList: [],
        uploadText: "支持mp4",
        artwroksTitle: "上传作品",
      },
      uploadForm: {
        title: "", // 作品名称
        author_id: "",
        type: null, // 作品类型
        show_type: 0,
        cate_id: "", // 作品分类
        album_id: "", // 专辑id
        price: 0,
        label_id: "",
      },
      o_uid:''
    };
  },
  computed: {
    ...mapGetters(["userStatistics", "userInfo", "token"]),
  },
  onLoad() {
    // this.month = parseTime(new Date(), "{y}-{m}-{d}");
    // this.monthStr = parseTime(new Date(), "{y}年{m}月");
    // console.log(new Date(), this.month )
    this.getOrderList();
    console.log(445, this.userInfo);
  },
  mounted() {
    let _this = this
    document.addEventListener("keydown", function (event) {
      if (event.key === "Enter" || event.keyCode === 13) {
        // 执行发送操作
        console.log("回车键被按下，执行发送操作");
        if(!_this.popShow){
          _this.secrchOrder()
          console.log(1)
        }
        if(_this.popShow){
          _this.sendMsg()
          console.log(12)
        }
      }
    });
  },
  deactivated() {
    clearInterval(this.timer);
  },
  methods: {
    previewImage(v, i) {
      if (i == 1) {
        uni.previewImage({
          current: v.yeDiaoInfos.file, // 当前显示图片的http链接
          urls: [v.yeDiaoInfos.file], // 需要预览的图片http链接列表
        });
      } else if (i == 2) {
        uni.previewImage({
          current: v.yeDiaoInfos.makePic, // 当前显示图片的http链接
          urls: [v.yeDiaoInfos.makePic], // 需要预览的图片http链接列表
        });
      }
    },
    playVideo() {
      // 获取video上下文
      this.videoContext = uni.createVideoContext("myVideo", this);
      // 请求全屏播放
      this.videoContext.requestFullScreen();
      // 开始播放视频（如果需要的话）
      this.videoContext.play();
    },
    fullscreenChange(e) {
      // 监听全屏变化
      if (!e.detail.fullScreen) {
        // 退出全屏时，可以停止播放视频（如果需要的话）
        // this.videoContext.pause();
        // 或者进行其他操作
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        var box = document.getElementById("box");
        box.scrollTop = box.scrollHeight + 100;
      });
      // this.$nextTick(() => {
      //   this.$refs.box.scrollTo(0, this.$refs.box.scrollHeight);
      // });
    },
    changeTabs(v) {
      if (v.id == 1) {
        this.getOrderList();
      }
      this.tabs.map((i) => {
        if (i.id == v.id) {
          i.isCheck = true;
        } else {
          i.isCheck = false;
        }
      });
      this.orderList = [];
    },
    onVideoTap(event) {
      // 触发点击事件时，将视频放大到全屏
      uni.createVideoContext(event.currentTarget.dataset.videoId, this).play();
    },
    secrchOrder(){
      this.getOrderList()
    },
    getOrderList() {
      uni.showToast({
        title: "加载中...",
        icon: "loading",
      });
      let p ={
        order_uid: this.o_uid
      }
      getOrderList(p)
        .then((result) => {
          uni.hideToast();

          result.data.records.map((i) => {
            console.log(i.yeDiaoInfo);
            i.time = parseTime(i.created_at, "{y}-{m}-{d} {h}:{m}:{s}");
            if (i.yeDiaoInfo) {
              i.yeDiaoInfos = JSON.parse(i.yeDiaoInfo);
            }
          });
          this.orderList = result.data.records;
          console.log(333, this.orderList);
        })
        .catch(() => {
          uni.hideToast();
        });
    },
    getOrderItem() {
      getOrderList({ order_uid: this.orderInfo.order_uid })
        .then((result) => {
          uni.hideToast();
          this.orderInfo = result.data.records[0];
          if (this.orderInfo.chat != "") {
            this.chatList = JSON.parse(this.orderInfo.chat);
          }

          this.chatList.map((i) => {
            if (i.u_name.length > 2) {
              i.u_name = i.u_name.substring(0, 2);
            }
          });
        })
        .catch(() => {
          uni.hideToast();
        });
    },
    openConcat(v) {
      this.popShow = true;
      if (v.chat != "") {
        this.chatList = JSON.parse(v.chat);
      }

      this.chatList.map((i) => {
        if (i.u_name.length > 2) {
          i.u_name = i.u_name.substring(0, 2);
        }
      });
      this.orderInfo = v;
      this.scrollToBottom();
      this.timer = setInterval(() => {
        this.getOrderItem();
      }, 3000);

      console.log(443535, this.orderInfo, this.chatList);
    },
    closePop() {
      this.popShow = false;
      this.orderInfo = null;
      clearInterval(this.timer);
      this.timer = null;
    },
    sendMsg() {
      console.log(this.userInfo, this.appletInfo);
      if (this.text == "") {
        uni.showToast({
          title: "请输入文字",
          icon: "none",
          mask: true,
        });
        return;
      }
      let msg = {
        u_name: this.userInfo.user_name,
        u_id: this.userInfo.id,
        text: this.text,
      };
      let arr = [];
      if (this.orderInfo.chat) {
        arr = JSON.parse(this.orderInfo.chat);
        arr.push(msg);
      } else {
        arr.push(msg);
      }

      let p = {
        ...this.orderInfo,
        chat: JSON.stringify(arr),
      };
      updataUserMemberOrder(p).then((res) => {
        this.getOrderItem();
        this.text = "";
        this.scrollToBottom();
      });
    },
    // 上传成功
    uploadSuccess(data, index, lists, name) {
      console.log(3434343, data[0].response.data.cover_path);
      if (data && data.length > 0) {
        uni.showToast({
          title: "上传成功",
          icon: "success",
          mask: true,
        });
        let info = JSON.parse(this.orderInfo.yeDiaoInfo);
        info.makePic = data[0].response.data.cover_path;
        this.orderInfo.yeDiaoInfo = JSON.stringify(info);
        let p = {
          ...this.orderInfo,
        };
        updataUserMemberOrder(p).then((res) => {
          console.log(444, res);
          this.getOrderList();
        });
      } else {
        uni.showToast({
          title: "至少选择一张图片或上传失败请重试！",
          icon: "none",
          mask: false,
        });
      }
    },
    uploadSuccessv(data, index, lists, name) {
      console.log("vvv", data[0].response.data.cover_path);
      if (data && data.length > 0) {
        uni.showToast({
          title: "上传成功",
          icon: "success",
          mask: true,
        });
        let info = JSON.parse(this.orderInfo.yeDiaoInfo);
        info.makeVideo = data[0].response.data.cover_path;
        this.orderInfo.yeDiaoInfo = JSON.stringify(info);
        let p = {
          ...this.orderInfo,
        };
        updataUserMemberOrder(p).then((res) => {
          console.log(444, res);
          this.getOrderList();
        });
      } else {
        uni.showToast({
          title: "至少选择一条视频或上传失败请重试！",
          icon: "none",
          mask: false,
        });
      }
    },
    // 选择图片
    chooseComplete(list) {
      // console.log(list)
    },
    submitWork(v, i) {
      console.log(22, this.$refs.uUpload, i);
      this.orderInfo = v;
      this.$refs.uUpload[i].upload();
      this.$refs.uploadv[i].upload();
    },
    downloadFile(v, i) {
      console.log(343434, v);
      return new Promise((rs, rj) => {
        const url = v.yeDiaoInfos.file;
        uni.downloadFile({
          url,
          success(d_res) {
            if (d_res && d_res.tempFilePath) {
              // #ifdef H5
              rs(d_res.tempFilePath);
              // #endif

              // #ifndef H5
              uni.saveFile({
                tempFilePath: d_res.tempFilePath,
                success(s_res) {
                  log("保存背景图成功:" + JSON.stringify(s_res));
                  if (s_res && s_res.savedFilePath) rs(s_res.savedFilePath);
                  else rs(d_res.tempFilePath);
                },
                fail(err) {
                  rs(d_res.tempFilePath);
                },
              });
              // #endif
            } else {
              rj("not find tempFilePath");
            }
          },
          fail(err) {
            rj(err);
          },
        });
      });
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.team-container {
  //   padding: 24rpx;
}
.tabList {
  width: 100%;
  height: 40px;
  line-height: 40px;
  display: flex;
  align-items: center;
  border: 1px solid #64c283;
  border-radius: 5px;
  .tab {
    height: 40px;
    line-height: 40px;
    width: 50%;
    text-align: center;
    border-radius: 5px;
  }
  .check {
    background-color: #64c283;
  }
}

.members-container {
  padding: 16rpx;
  .earning-item {
    padding: 24rpx;
    border-radius: 16rpx;
    box-shadow: 0rpx 1rpx 10rpx 2rpx #d5dcf0;
    background: #fff;
    color: #333;
    margin: 5px 0;
    position: relative;
    min-height: 200rpx;
    .item_s {
      margin: 3px 0;
      display: flex;
      align-items: center;
    }
    .concatU {
      width: 90px;
      height: 35px;
      text-align: center;
      line-height: 35px;
      background-color: rgb(100, 194, 131);
      border-radius: 10px;
      position: absolute;
      right: 10px;
      color: #fff;
      top: 60px;
    }
    .upload {
      display: flex;
      align-items: center;
    }
    .submitbtn {
      width: 90px;
      height: 35px;
      text-align: center;
      line-height: 35px;
      background-color: rgba(100, 194, 131, 0.897);
      border-radius: 10px;
      position: absolute;
      right: 10px;
      color: #fff;
      bottom: 15px;
    }
  }
}
.empty {
  text-align: center;
}
.popup {
  width: 90%;
  height: 70%;
  background-color: #fff;
  position: fixed;
  top: 10%;
  left: 5%;
  z-index: 1112;
  border-radius: 7px;
  .back {
    padding-bottom: 16rpx;
    height: 100%;
    border-radius: 7px;
    background-color: #ffffff;
    .chart {
      padding: 20rpx;
      width: 100%;
      height: 90%;
      // margin-bottom: 5px;
      overflow-y: auto;
      .chatList {
        margin-top: 5px;
        .u_name {
          width: 40px;
          min-width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          border-radius: 20px;
          color: #fff;
          font-size: 14px;
        }
        .rightText {
          .u_name {
            background-color: #a5cc79;
          }
          display: flex;
          align-items: center;
          float: right;
          .textBox {
            background: #88b632;
            border-radius: 5px;
            margin-right: 5px;
            padding: 10rpx;
          }
        }
        .leftText {
          display: flex;
          align-items: center;
          float: left;
          .u_name {
            background-color: #99ccff;
          }
          .textBox {
            background: #cccccc;
            border-radius: 5px;
            margin-left: 5px;
            padding: 10rpx;
          }
        }
      }
    }
    .submit {
      display: flex;
      justify-content: start;
      align-items: center;
      border-top: 1px solid #ccc;
      padding: 16rpx 12rpx 0 12rpx;
      // position: absolute;
      // bottom:5px;
      .text_inp {
        width: 100%;
        border: 1px solid rgb(221, 221, 221);
        height: 30px;
        line-height: 30px;
        border-radius: 5px;
      }
      .submitBtn {
        width: 60px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        color: #fff;
        background-color: #88b632;
        margin: 0 auto;
        border-radius: 5px;
        font-size: 15px;
        margin-left: 5px;
      }
    }
  }
  .closeIcon {
    position: absolute;
    bottom: -35px;
    width: 30px;
    height: 30px;
    left: 45%;
  }
}
.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1111;
}
.splitLine{
  width: 100%;
  height: 2px;
  background: #ccc;
}
.serchbox{
  
  padding:16rpx;
}
.serch_box{
  background: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
    box-shadow: 0rpx 1rpx 10rpx 2rpx #d5dcf0;
  label{
    display: block;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  .box{
    display: flex;
    align-items: center;
  }
  .text_inp {
        width: 100%;
        border: 1px solid rgb(221, 221, 221);
        height: 30px;
        line-height: 30px;
        border-radius: 5px;
      }
      .submitBtn {
        width: 60px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        color: #fff;
        background-color: rgb(100, 194, 131);
        margin: 0 auto;
        border-radius: 5px;
        font-size: 15px;
        margin-left: 5px;
      }
}

</style>
  